import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import simple.GpsDock;
import simple.GpsUnit;
import simple.IGpsListener;
import simple.enums.BaudRate;
import simple.enums.DataBits;
import simple.enums.Parity;
import simple.enums.StopBits;
import Utils.Utils;

public class Application extends JFrame {
	private static final long serialVersionUID = 1L;

	SerialPort port;

	InputStream inputStream;
	Thread readThread;

	StringBuilder data = new StringBuilder();

	boolean dataAvailable = false;

	JButton connectButton;
	JButton disconnectButton;
	JList commList;

	JButton sendMessage;
	
	GpsDock dock;
	GpsUnit unit;
	
	public Application(){
		super("JSpoorloos");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(new BorderLayout());
		
		dock = new GpsDock();
		unit = new GpsUnit(BaudRate._115200,DataBits.EIGHT, StopBits.ONE, Parity.NONE);
		dock.setUnit(unit);

		DefaultListModel model = new DefaultListModel();
		
		// Get the CommPortIdentifiers:
		for (CommPortIdentifier commPort : dock.getCommPortIdentifiers()) {
			// Only include the serial ports that are not currently owned by any software:
			if (commPort.getPortType() == CommPortIdentifier.PORT_SERIAL && !commPort.isCurrentlyOwned()) {
				model.addElement(commPort);
			}
		}

		commList = new JList(model);
		this.add(commList, BorderLayout.CENTER);
		commList.setCellRenderer(new ListCellRenderer() {

			@Override
			public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
				try {
					JLabel label = new JLabel();
					label.setOpaque(true);
					label.setText(((CommPortIdentifier) value).getName());
					if (isSelected) {
						label.setForeground(list.getSelectionForeground());
						label.setBackground(list.getSelectionBackground());
					} else {
						label.setForeground(list.getForeground());
						label.setBackground(list.getBackground());
					}
					return label;
				} catch (ClassCastException e) {
					System.out.println(e.getMessage());
				}
				return null;
			}

		});
		commList.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				if (!e.getValueIsAdjusting()) {
					System.out.println(e.getSource());
				}
			}

		});

		JPanel buttonPanel = new JPanel(new BorderLayout());
		this.add(buttonPanel, BorderLayout.SOUTH);

		connectButton = new JButton("Connect");
		buttonPanel.add(connectButton, BorderLayout.NORTH);
		connectButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ae) {
				if (commList.getSelectedValue() != null) {
					try {
						CommPortIdentifier commPortId = (CommPortIdentifier) commList.getSelectedValue();
						dock.openCommPort(commPortId);
						
						dock.clearGpsListeners();
						dock.addGpsListener(new IGpsListener(){
							@Override
							public void sentenceFound(String sentence) {
								System.out.println(sentence);
							}
						});
						dock.connect();
						commList.setBackground(Color.ORANGE);
					} catch (PortInUseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (UnsupportedCommOperationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});

		disconnectButton = new JButton("Disconnect");
		buttonPanel.add(disconnectButton, BorderLayout.CENTER);
		disconnectButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (dock != null) {
					dock.disconnect();
					commList.setBackground(Color.WHITE);
				}
			}
		});

		sendMessage = new JButton("Send message");
		buttonPanel.add(sendMessage, BorderLayout.SOUTH);
		sendMessage.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					OutputStream out = dock.getOutputStream();
					 String NMEA = "$" + "PMTK182,7," + Integer.toHexString(0) + "," + Integer.toHexString(65536) + "*";
//					String NMEA = "$" + "PMTK182,7," + Integer.toHexString(0) + "," + Integer.toHexString(20) + "*";
//					String NMEA = "$" + "PMTK182,1,3,1" + Integer.toHexString(0) + "," + Integer.toHexString(20) + "*";
//					String NMEA = "$" + "PMTK182,6,1*";
					NMEA += Utils.Checksum(NMEA) + "\r\n";
					// '\015', '\012'
					out.write(NMEA.getBytes());

				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});
	}
	
	public static void main(String[] args) {
//		GpsDock d = new GpsDock();
//		GpsUnit u = new GpsUnit(BaudRate._115200,DataBits.EIGHT, StopBits.ONE, Parity.NONE);
//		d.setUnit(u);
//		
//		d.addGpsListener(new IGpsListener(){
//			@Override
//			public void sentenceFound(String sentence) {
//				System.out.println(sentence);
//			}});
//		
//		for (CommPortIdentifier id : d.getCommPortIdentifiers()) {
//			if(id.getName().equals("COM4")){
//				try {
//					d.openCommPort(id);
//					d.connect();
//				} catch (PortInUseException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} catch (UnsupportedCommOperationException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				
//			}
//		}
		
		Application a = new Application();
		a.setSize(300, 400);
		a.setVisible(true);
	}
}
